<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <style>
        /* 基础样式 */
        * {
            box-sizing: border-box;
            margin: 0;

        }

        body {
            font-family: '微软雅黑';
            background: rgb(255, 255, 255);

        }

        /* 双栏布局 */
        .container {
            display: grid;
            grid-template-columns: 1fr 1.5fr;
            gap: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 学生列表 */
        .student-list {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* 床位地图 */
        .bed-map {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* 学生卡片 */
        .student-card {
            background: #fff;
            border: 2px dashed #e8e8e8;
            padding: 12px;
            margin-bottom: 10px;
            border-radius: 6px;
            cursor: grab;
            transition: transform 0.2s;
        }

        .student-card:hover {
            transform: translateX(5px);
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        }

        /* 3D床位效果 */
        .bed-item {
            background: #1890ff;
            color: white;
            padding: 15px;
            border-radius: 4px;
            margin: 5px;
            cursor: pointer;
            transition: all 0.3s;
            position: relative;
        }

        .bed-item:hover {
            transform: perspective(500px) translateZ(20px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        /* 状态指示灯 */
        .status-led {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }

        .available {
            background: #52c41a;
        }

        .occupied {
            background: #ff4d4f;
        }

        /* 动态搜索框 */
        .search-box {
            position: relative;
            margin-bottom: 20px;
        }

        .search-box input {
            width: 100%;
            padding: 10px 40px 10px 15px;
            border: 2px solid #1890ff;
            border-radius: 25px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .search-box input:focus {
            box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
        }

        /* 操作面板 */
        .action-panel {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 左侧：未分配学生 -->
    <div class="student-list" id="student-list">
        <h2>👥 待分配学生</h2>
        <div class="search-box">
            <input type="text" placeholder="🔍 搜索学生..." id="searchInput">
        </div>
        <div id="div2"></div>

    </div>

    <!-- 右侧：床位分配 -->
    <div class="bed-map">
        <h2>🛏️ 床位地图</h2>
        <div class="action-panel">
            <select class="building-select" id="dong">

            </select>

            <select class="building-select" id="lou">
                <option value="1">1楼</option>
                <option value="2">2楼</option>
                <option value="3">3楼</option>
                <option value="4">4楼</option>
            </select>

            <select class="building-select" id="fang" onclick="query3()">
                <option value="101">101房</option>
                <option value="102">102房</option>
                <option value="103">103房</option>
                <option value="104">104房</option>
                <option value="105">105房</option>
                <option value="106">106房</option>
                <option value="106">107房</option>
            </select>

        </div>

        <!-- 床位可视化 -->
        <div class="bed-layout">
            <div class="bed-grid">
                <div class="bed-item">

                </div>

            </div>
        </div>
    </div>
</div>

<!-- 分配弹窗 -->
<div class="assignment-modal">
    <div class="modal-content">
        <h3>✨ 分配魔法</h3>
        <p>将学生拖放到目标床位</p>
        <div class="confetti-animation"></div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>


    // 拖拽初始化（使用事件委托处理动态元素）
    document.getElementById('div2').addEventListener('mousedown', function (e) {
        const target = e.target.closest('.student-card');
        if (!target) return;

        const rect = target.getBoundingClientRect();
        const offsetX = e.clientX - rect.left;
        const offsetY = e.clientY - rect.top;

        // 创建拖动克隆体
        const clone = target.cloneNode(true);
        clone.style.position = 'absolute';
        clone.style.opacity = '0.8';
        clone.style.pointerEvents = 'none';
        clone.style.transform = 'rotate(5deg)';
        document.body.appendChild(clone);

        function onMouseMove(e) {
            clone.style.left = e.clientX - offsetX + 'px';
            clone.style.top = e.clientY - offsetY + 'px';
        }

        function onMouseUp(e) {
            document.removeEventListener('mousemove', onMouseMove);
            document.removeEventListener('mouseup', onMouseUp);

            const bedItem = document.elementFromPoint(e.clientX, e.clientY).closest('.bed-item');

            if (bedItem) {
                // 获取房间ID（只要value的第三个字符）
                const roomValue = $('#fang').val(); // 获取select的值，如"106"
                const roomId = roomValue.substring(2); // 取第三个字符，即"6"

                // 获取床位名称（如A01）
                const roomName = bedItem.getAttribute('data-bed-number');

                console.log("roomId:", roomId, "roomName:", roomName);

                if (bedItem.querySelector('.student-info')) {
                    // 更新床位状态
                  //  bedItem.innerHTML = '<div class="status-led occupied" data-student-id="'+target.dataset.studentId+'">'+target.dataset.studentNumber+'</div>';
                    query3();
                    add(target, roomId, roomName);
                    bedItem.classList.add('occupied');
                    target.remove();
                }
            }

            clone.remove();

        }

        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    });

    // 床位拖放区设置
    document.querySelectorAll('.bed-item').forEach(item => {
        item.addEventListener('dragover', e => {
            e.preventDefault();
            item.style.transform = 'scale(1.05)';
        });

        item.addEventListener('dragleave', () => {
            item.style.transform = 'none';
        });
    });

    // 趣味功能：庆祝特效
    function showConfetti() {
        const colors = ['#ff4d4f', '#52c41a', '#1890ff', '#faad14'];
        for (let i = 0; i < 50; i++) {
            const confetti = document.createElement('div');
            confetti.style.cssText = `
                width: 6px; height: 6px;
                background: ${colors[Math.floor(Math.random()*colors.length)]};
                position: absolute;
                border-radius: 2px;
                animation: confetti 1s ease-out;
            `;
            document.body.appendChild(confetti);

            setTimeout(() => confetti.remove(), 1000);
        }
    }

    // 搜索功能
    document.getElementById('searchInput').addEventListener('input', function (e) {
        const searchTerm = e.target.value.toLowerCase();
        document.querySelectorAll('.student-card').forEach(card => {
            const text = card.innerText.toLowerCase();
            card.style.display = text.includes(searchTerm) ? 'block' : 'none';
        });
    });

    $(document).ready(function () {
        query();
        query2();
    });



    // 全局变量存储当前选中的楼栋ID
    let currentBuildingId;
    function query2() {
        console.log("query2")
        $.get("<%=request.getContextPath()%>/Dorm_buildingsController", {
            op: "cx",
        }, function (data) {
            show2(data);
            // 默认选中第一个楼栋并查询房间
            if (data && JSON.parse(data).length > 0) {
                currentBuildingId = JSON.parse(data)[0].building_id;
                query3();
            }
        });
    }

    function show2(data) {
        console.log("show2")
        let data2 = JSON.parse(data);
        let html = "";
        $.each(data2, function (index, emp) {
            html += '<option data-id="' + emp.building_id + '">' + emp.building_name + '</option>';
        });
        $("#dong").html(html).change(function () {
            // 当选择变化时更新当前楼栋ID并查询房间
            currentBuildingId = $(this).find("option:selected").data("id");

        });
    }

    function query3() {
        console.log("query3")
        if (!currentBuildingId) return;
        let roomid=$('#fang').val();
        console.log(roomid);
        let floor=$('#lou').val();
        $.get("<%=request.getContextPath()%>/Dorm_roomsController", {
            op: "buildingcx",
            id: currentBuildingId,
            roomnumberid:roomid,
            floor:floor,
        }, function (data) {
            show3(data);
        });
    }

    <%--    ${room.is_occupied ? 'occupied' : 'available'}--%>


    function show3(data) {
        console.log("show3")
        let rooms = JSON.parse(data);
        let html = "";
        const roomValue = $('#fang').val(); // 获取select的值，如"106"
        const roomId = roomValue.substring(2); // 取第三个字符，即"6"

        $.each(rooms, function (index, room) {
            // 根据capacity生成床位编号
            var bedHtml = '';
            for(var i = 1; i <= room.capacity; i++) {
                var bedNumber = (i < 10) ? '0' + i : i;
                let xh = cx(roomId,"A"+bedNumber);
                if(xh!="null"){
                    bedHtml += '<div class="bed-simple">' +
                        '<div class="bed-title">A' + bedNumber + '床</div>' +
                        '<div class="bed-detail">' +
                        '<span class="bed-student">' + xh + '</span>' +
                        '<span class="bed-status">已入住</span>' +
                        '</div>' +
                        '</div>';
                }else{
                    // 格式化编号为两位数，如01,02
                    bedHtml += '<div class="bed-item" data-room-id="'+room.room_id+'" data-room-number="'+room.room_number+'" data-bed-number="A'+bedNumber+'">' +
                        '<div class="status-led"></div>' +
                        'A' + bedNumber + '床' +
                        '<div class="student-info"></div>' +
                        '</div>';

                }
            }
            html += bedHtml;
        });

        // 更新DOM
        $(".bed-grid").html(html);
    }

    function cx(room_id, bed_number) {
        let sid;
        $.ajax({
            url: "<%=request.getContextPath()%>/Dorm_bedsController",
            type: "GET",
            data: {
                op: "cx",
                room_id: room_id,
                bed_number: bed_number
            },
            async: false, // 设置为同步
            success: function(data) {
                sid = data;
            }
        });
        return sid;
    }






    function add(target,roomId,roomName) {

        const id = target.dataset.studentId; // 直接获取

        $.get("<%=request.getContextPath()%>/Dorm_bedsController", {
            op: "add",
            roomid: roomId,
            name:roomName,
            student:id,
        }, function (data) {
             alert(data)
            query();
        });


    }



    function query() {
        console.log("执行query")
        $.get("<%=request.getContextPath()%>/StudentsController", {
            op: "query",
        }, function (data) {
            console.log(data)
            show(data);
        })
    }


    function show(data) {
        console.log("show")
        let data1 = JSON.parse(data);
        let htmls = "";
        $.each(data1, function (index, emp) {
            htmls += '<div class="student-card" draggable="true" data-student-id="' + emp.student_id + '"    data-student-number="'+emp.student_number+'">' +
                '<div class="status-led available"></div>' +
                emp.student_number + '-' + emp.name + '(' + emp.gender + ')' +
                '</div>';
        });
        $("#div2").html(htmls);
    }


</script>

<style>
    /* 庆祝动画 */
    @keyframes confetti {
        0% {
            transform: translateY(0) rotate(0);
            opacity: 1;
        }
        100% {
            transform: translateY(500px) rotate(360deg);
            opacity: 0;
        }
    }

    /* 楼层选择联动 */
    .building-select, .floor-select {
        padding: 8px 12px;
        border: 2px solid #1890ff;
        border-radius: 20px;
        background: white;
        cursor: pointer;
    }

    /* 床位网格布局 */
    .bed-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 15px;
        margin-top: 20px;
    }

    /* 动态颜色变化 */
    .available-bed {
        background: #1890ff;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% {
            opacity: 0.8;
        }
        50% {
            opacity: 1;
        }
        100% {
            opacity: 0.8;
        }
    }


</style>
<style>
    .bed-simple {
        display: inline-block;
        width: 120px;
        margin: 8px;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        background: #fff;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        font-family: Arial, sans-serif;
    }

    .bed-title {
        padding: 8px;
        background: #f5f5f5;
        font-weight: bold;
        text-align: center;
        border-bottom: 1px solid #e0e0e0;
        color: #333;
    }

    .bed-detail {
        padding: 8px;
        text-align: center;
    }

    .bed-student {
        display: block;
        color: #555;
        font-size: 14px;
        margin-bottom: 4px;
    }

    .bed-status {
        display: inline-block;
        padding: 2px 8px;
        background: #ffebee;
        color: #d32f2f;
        border-radius: 10px;
        font-size: 12px;
    }

    /* 悬停效果 */
    .bed-simple:hover {
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
        border-color: #bdbdbd;
    }
</style>
</body>
</html>